package com.example.kiratest.notify.Test;

import com.alibaba.fastjson.JSON;
import com.example.kiratest.notify.DingtalkNotifier;
import com.example.kiratest.notify.Enum.MsgTypeEnum;
import com.example.kiratest.notify.POJO.CardRequest;
import com.example.kiratest.notify.POJO.DingtalkColumnsItem;
import com.example.kiratest.notify.POJO.DingtalkRowsItem;
import com.example.kiratest.notify.POJO.DingtalkTableItem;
import com.example.kiratest.realize.mapper.PhaAppMapper;
import com.example.kiratest.realize.mapper.PhaTradeMapper;
import com.example.kiratest.realize.pojo.PhaApp;
import com.example.kiratest.realize.pojo.PhaTrade;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;
import java.util.stream.Collectors;

//测试爬取官网Package包信息,和数据库的Package包版本version进行对比,推送Version不同的东西到钉钉群聊
@Component
@Slf4j
public class GetByVersionTest {
    @Autowired
    PhaTradeMapper phaTradeMapper;

    @Autowired
    PhaAppMapper phaAppMapper;

    public String execute() throws URISyntaxException {

        List<PhaTrade> list = phaTradeMapper.list();
        //查出正在跑单的PackageName,投放量cap!=0,stuatus!=3,3是我们的暂停状态
        List<String> listPackageName = list.stream()
//                .filter(trade -> trade.getCap() != 0)
//                .filter(trade -> trade.getTradeStatus() != 3)
                .map(PhaTrade::getPackageName)
                .distinct()//对PackageName去重
                .collect(Collectors.toList());

        //把所有Apps的信息存到Map
        List<PhaApp> listPhaApps =phaAppMapper.list();
        Map<String,PhaApp> map=new HashMap<>();
        for(PhaApp phaApp:listPhaApps){
            map.put(phaApp.getPackageName(),phaApp);
        }



        GetVersionUtil pythonUtil=new GetVersionUtil();//python查看版本工具类
        List<DingtalkRowsItem> dingtalkRowsItemList=new ArrayList<>();

        //只收集正在跑单的PackAge的信息的准备发送给钉钉的数据
        for(String packageName:listPackageName){
            PhaApp phaApp = map.get(packageName);
            if(phaApp==null) continue;
            DingtalkRowsItem dingtalkRowsItem=new DingtalkRowsItem();


            //调用python查看版本的工具类,找出googleplay version
            String googlePlayVersionCode = pythonUtil.execute(packageName);

            String apkcomboVersionCode = null;
            if(googlePlayVersionCode==null||googlePlayVersionCode.trim().equalsIgnoreCase("Varies with Device")){
                 apkcomboVersionCode = apkCrawl("https://apkcombo.app/zh/mobile-legends/" + packageName, "apkcombo");
            }


            String apkmirrorVersionCode=null;
            if(apkcomboVersionCode==null){
                apkmirrorVersionCode = apkCrawl("https://www.apkmirror.com/?s=" + packageName, "apkmirror");
            }



            Boolean status=false;
            //数据库中的版本号
            String innerVersionCode=phaApp.getVersionCode();
            if(googlePlayVersionCode!=null&&!googlePlayVersionCode.trim().equalsIgnoreCase("Varies with Device")){
                if(innerVersionCode.equals(googlePlayVersionCode)) {
                    status=true;
                }
            }else if (apkcomboVersionCode!=null){
                if(!innerVersionCode.equals(apkcomboVersionCode)){
                    status=true;
                }
            }else if(apkmirrorVersionCode!=null){
                if(!innerVersionCode.equals(apkmirrorVersionCode)){
                status=true;
                }
            }
//            说明版本号不同,要推送这个信息
            if(status==true){
                dingtalkRowsItem.setPackageName(packageName)
                        .setGooglePlayVersionCode(googlePlayVersionCode)
                        .setInnerVersionCode(innerVersionCode)
                        .setApkcomboVersionCode(apkcomboVersionCode)
                        .setApkmirrorVersionCode(apkmirrorVersionCode);
                dingtalkRowsItemList.add(dingtalkRowsItem);
            }

        }


        //CardRequest
        CardRequest pbNotifierMsg = crawlPkgMsg();
        //构建CardRequest
        pbNotifierMsg.getCardData().getCardParamMap().getTableBean().setData(dingtalkRowsItemList);
        DingtalkTableItem tableBean = pbNotifierMsg.getCardData().getCardParamMap().getTableBean();
        pbNotifierMsg.getCardData().getCardParamMap().setTable(JSON.toJSONString(tableBean));
        pbNotifierMsg.setOpenSpaceId(MsgTypeEnum.NOTIFY2.getOpenSpaceId());//群聊场域Id
        pbNotifierMsg.setCardTemplateId("824ef344-4d2d-4b12-9ff9-d86ab943e67c.schema");//卡片模板Id
        pbNotifierMsg.setOutTrackId(UUID.randomUUID().toString());//请求唯一Id

        //将CradRequest对象变成Json字符串
        String jsonString = JSON.toJSONString(pbNotifierMsg);

        DingtalkNotifier dingtalkNotifier = new DingtalkNotifier();

        dingtalkNotifier.notify(jsonString, null);

        return "执行完毕";
    }






    /**
     * 我们主要有5个参数 packageName,gp商城apk版本,当前apk版本,apkcombo apk版本
     * setAlias是往里面放数据
     * setAliasName是数据展示的时候我们的名字
     * @return
     */
    public CardRequest crawlPkgMsg() {
        List<DingtalkColumnsItem> columnsItems = new ArrayList<>();
        columnsItems.add(new DingtalkColumnsItem().setDataType("STRING")
                .setAlias("packageName").setAliasName("packageName").setWeight(35));
        columnsItems.add(new DingtalkColumnsItem().setDataType("STRING")
                .setAlias("googlePlayVersionCode").setAliasName("gp商城apk版本").setWeight(22));
        columnsItems.add(new DingtalkColumnsItem().setDataType("STRING")
                .setAlias("innerVersionCode").setAliasName("当前apk版本").setWeight(22));
        columnsItems.add(new DingtalkColumnsItem().setDataType("STRING")
                .setAlias("apkcomboVersionCode").setAliasName("apkcombo_apk版本").setWeight(22));
        columnsItems.add(new DingtalkColumnsItem().setDataType("STRING")
                .setAlias("apkmirrorVersionCode").setAliasName("apkmirror_apk版本").setWeight(22));
        return new CardRequest("目标包版本信息通知", columnsItems);
    }

    //从不同应用平台抓取应用版本信息
    //确定合适的CSS选择器来定位版本信息,抓取目标网页的HTML内容,使用CSS选择器提取版本号,处理可能出现的异常情况
    private String apkCrawl(String url,String appPlatform) {
        String queryInfo = appPlatform.equals("apkcombo") ? "div.version" : "div.infoSlide .infoSlide-name:contains(Version:) + .infoSlide-value";
        if(appPlatform.equals("googleplay")){
            queryInfo = "div.reAt0";
        }
        try {
            Document document = Jsoup.connect(url).get();
            Element versionElement = document.selectFirst(queryInfo);
            if(versionElement != null) {
                return versionElement.text();
            }
        } catch (IOException e) {
            log.error("==== apk crawl func ==== execute err:", e);
        }
        return "";
    }
}
